/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mani.thindownloadmanager.app;

import com.mani.thindownloadmanager.app.utils.HiLogUtil;
import com.mani.thindownloadmanager.app.utils.ImageUtil;
import com.thin.downloadmanager.DefaultRetryPolicy;
import com.thin.downloadmanager.DownloadRequest;
import com.thin.downloadmanager.DownloadStatusListenerV1;
import com.thin.downloadmanager.ThinDownloadManager;
import com.thin.downloadmanager.RetryPolicy;
import com.thin.downloadmanager.DownloadManager;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;

import ohos.agp.components.Button;
import ohos.agp.components.Image;
import ohos.agp.components.ProgressBar;
import ohos.agp.components.Text;

import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.agp.window.service.Window;

import ohos.global.config.ConfigManager;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.IOException;
import java.util.Optional;

/**
 * MainAbility
 */
public class MainAbility extends Ability {

    private ThinDownloadManager downloadManager;
    private static final int DOWNLOAD_THREAD_POOL_SIZE = 5;
    private static final String FILE1 = "https://httpbin.org/image/png";
    private static final String FILE2 = "https://httpbin.org/image/jpeg";
    private static final String FILE3 = "https://httpbin.org/image/webp";
    private static final String FILE4 = "https://media.w3.org/2010/05/sintel/trailer.mp4"; // http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4
    private static final String FILE5 = "https://httpbin.org/robots.txt";

    private int downloadId1;
    private int downloadId2;
    private int downloadId3;
    private int downloadId4;
    private int downloadId5;
    private DownloadRequest downloadRequest1;
    private DownloadRequest downloadRequest2;
    private DownloadRequest downloadRequest3;
    private DownloadRequest downloadRequest4;
    private DownloadRequest downloadRequest5;
    private File filesDirs1;
    private File filesDirs2;
    private File filesDirs3;
    private File filesDirs4;
    private File filesDirs5;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_main);
        DisplayManager displayManager = DisplayManager.getInstance();
        Optional<Display> defaultDisplay = displayManager.getDefaultDisplay(this);
        Display display = defaultDisplay.get();
        DisplayAttributes displayAttributes = display.getAttributes();
        WindowManager windowManager = WindowManager.getInstance();
        Window window = windowManager.getTopWindow().get();
        ConfigManager configManager = getResourceManager().getConfigManager();
        Image imageView1 = (Image) findComponentById(ResourceTable.Id_imageView1);
        Button downloadImage1 = (Button) findComponentById(ResourceTable.Id_bt_start1);
        ProgressBar progressBar1 = (ProgressBar) findComponentById(ResourceTable.Id_progressBar1);
        Image imageView2 = (Image) findComponentById(ResourceTable.Id_imageView2);
        Button downloadImage2 = (Button) findComponentById(ResourceTable.Id_bt_start2);
        ProgressBar progressBar2 = (ProgressBar) findComponentById(ResourceTable.Id_progressBar2);
        Image textView3 = (Image) findComponentById(ResourceTable.Id_textView3);
        Button downloadImage3 = (Button) findComponentById(ResourceTable.Id_bt_start3);
        ProgressBar progressBar3 = (ProgressBar) findComponentById(ResourceTable.Id_progressBar3);
        Text textView4 = (Text) findComponentById(ResourceTable.Id_textView4);
        Button downloadImage4 = (Button) findComponentById(ResourceTable.Id_bt_start4);
        ProgressBar progressBar4 = (ProgressBar) findComponentById(ResourceTable.Id_progressBar4);
        Text textView5 = (Text) findComponentById(ResourceTable.Id_textView5);
        Button downloadImage5 = (Button) findComponentById(ResourceTable.Id_bt_start5);
        ProgressBar progressBar5 = (ProgressBar) findComponentById(ResourceTable.Id_progressBar5);
        Button downAll = (Button) findComponentById(ResourceTable.Id_bt_start6);
        Button cancelAll = (Button) findComponentById(ResourceTable.Id_bt_start7);
        progressBar1.setProgressValue(0);
        progressBar1.setMaxValue(100);
        progressBar2.setProgressValue(0);
        progressBar2.setMaxValue(100);
        progressBar3.setProgressValue(0);
        progressBar3.setMaxValue(100);
        progressBar4.setProgressValue(0);
        progressBar4.setMaxValue(100);
        progressBar5.setProgressValue(0);
        progressBar5.setMaxValue(100);

        // 初始化下载器
        downloadManager = new ThinDownloadManager(DOWNLOAD_THREAD_POOL_SIZE);
        RetryPolicy retryPolicy = new DefaultRetryPolicy();
        downloadImage1(imageView1, downloadImage1, progressBar1, retryPolicy);
        downloadImage2(imageView2, downloadImage2, progressBar2, retryPolicy);
        downloadImage3(textView3, downloadImage3, progressBar3, retryPolicy);
        downloadImage4(textView4, downloadImage4, progressBar4);
        downloadImage5(textView5, downloadImage5, progressBar5);

        download(downAll, cancelAll);
    }

    private void download(Button downAll, Button cancelAll) {
        downAll.setClickedListener(component -> {
            downloadManager.cancelAll();
            downloadId1 = downloadManager.add(downloadRequest1);
            downloadId2 = downloadManager.add(downloadRequest2);
            downloadId3 = downloadManager.add(downloadRequest3);
            downloadId4 = downloadManager.add(downloadRequest4);
            downloadId5 = downloadManager.add(downloadRequest5);
        });
        cancelAll.setClickedListener(component -> {
            downloadManager.cancelAll();
        });
    }

    private void downloadImage5(Text textView5, Button downloadImage5, ProgressBar progressBar5) {
        RetryPolicy retryPolicy; // 下载图片1
        Uri downloadUri4 = Uri.parse(FILE5);
        filesDirs5 = new File(getCacheDir(), "/master5.txt");
        Uri destinationUri4 = Uri.getUriFromFile(filesDirs5);
        retryPolicy = new DefaultRetryPolicy();
        downloadRequest5 = new DownloadRequest(downloadUri4)
                .setDestinationURI(destinationUri4)
                .setPriority(DownloadRequest.Priority.HIGH)
                .setRetryPolicy(retryPolicy)
                .setDownloadContext("Download5")
                .setStatusListener(new DownloadStatusListenerV1() {
                    @Override
                    public void onDownloadComplete(DownloadRequest downloadRequest) {
                        try {
                            textView5.setText(filesDirs5.getCanonicalPath());
                        } catch (IOException e) {
                            HiLogUtil.error(e.toString());
                        }
                        progressBar5.setProgressValue(100);
                        HiLogUtil.error("onDownloadComplete---完成下载-----" + filesDirs5.getTotalSpace() + "------");
                    }

                    @Override
                    public void onDownloadFailed(DownloadRequest downloadRequest, int errorCode, String errorMessage) {
                        HiLogUtil.error("onDownloadFailed---" + errorCode + "-----" + errorMessage + "-----");
                    }

                    @Override
                    public void onProgress(DownloadRequest downloadRequest, long totalBytes, long downloadedBytes, int progress) {
                        HiLogUtil.error("onProgress---" + progress + "-----");
                        progressBar5.setProgressValue(progress);
                    }
                });

        downloadImage5.setClickedListener(component -> {
            if (downloadManager.query(downloadId5) == DownloadManager.STATUS_NOT_FOUND) {
                downloadId5 = downloadManager.add(downloadRequest5);
            }
        });
    }

    private void downloadImage4(Text textView4, Button downloadImage4, ProgressBar progressBar4) {
        RetryPolicy retryPolicy; // 下载图片1
        Uri downloadUri3 = Uri.parse(FILE4);
        filesDirs4 = new File(getCacheDir(), "/video.mp4");
        Uri destinationUri3 = Uri.getUriFromFile(filesDirs4);
        retryPolicy = new DefaultRetryPolicy(3000, 2, 3f);
        downloadRequest4 = new DownloadRequest(downloadUri3)
                .setDestinationURI(destinationUri3)
                .setPriority(DownloadRequest.Priority.IMMEDIATE)
                .setRetryPolicy(retryPolicy)
                .setDownloadResumable(true)
                .setDownloadContext("Download4")
                .setStatusListener(new DownloadStatusListenerV1() {
                    @Override
                    public void onDownloadComplete(DownloadRequest downloadRequest) {
                        try {
                            textView4.setText(filesDirs4.getCanonicalPath());
                        } catch (IOException e) {
                            HiLogUtil.error(e.toString());
                        }
                        // textView3.setPixelMap(ImageUtil.getPixelMapByFile(filesDirs4));
                        HiLogUtil.error("onDownloadComplete---完成下载-----" + filesDirs4.getTotalSpace() + "------");
                    }

                    @Override
                    public void onDownloadFailed(DownloadRequest downloadRequest, int errorCode, String errorMessage) {
                        HiLogUtil.error("onDownloadFailed---" + errorCode + "-----" + errorMessage + "-----");
                    }

                    @Override
                    public void onProgress(DownloadRequest downloadRequest, long totalBytes, long downloadedBytes, int progress) {
                        HiLogUtil.error("onProgress---" + progress + "-----");
                        progressBar4.setProgressValue(progress);
                    }
                });

        downloadImage4.setClickedListener(component -> {
            if (downloadManager.query(downloadId4) == DownloadManager.STATUS_NOT_FOUND) {
                downloadId4 = downloadManager.add(downloadRequest4);
            }
        });
    }

    private void downloadImage3(Image textView3, Button downloadImage3, ProgressBar progressBar3, RetryPolicy retryPolicy) {
        // 下载图片1
        Uri downloadUri2 = Uri.parse(FILE3);
        filesDirs3 = new File(getCacheDir(), "/master3.jpg");
        Uri destinationUri2 = Uri.getUriFromFile(filesDirs3);
        downloadRequest3 = new DownloadRequest(downloadUri2)
                .setDestinationURI(destinationUri2)
                .setPriority(DownloadRequest.Priority.LOW)
                .setRetryPolicy(retryPolicy)
                .setDownloadContext("Download3")
                .setStatusListener(new DownloadStatusListenerV1() {
                    @Override
                    public void onDownloadComplete(DownloadRequest downloadRequest) {
                        textView3.setPixelMap(ImageUtil.getPixelMapByFile(filesDirs3));
                        HiLogUtil.error("onDownloadComplete---完成下载-----" + filesDirs3.getTotalSpace() + "------");
                    }

                    @Override
                    public void onDownloadFailed(DownloadRequest downloadRequest, int errorCode, String errorMessage) {
                        HiLogUtil.error("onDownloadFailed---" + errorCode + "-----" + errorMessage + "-----");
                    }

                    @Override
                    public void onProgress(DownloadRequest downloadRequest, long totalBytes, long downloadedBytes, int progress) {
                        HiLogUtil.error("onProgress---" + progress + "-----");
                        progressBar3.setProgressValue(progress);
                    }
                });

        downloadImage3.setClickedListener(component -> {
            if (downloadManager.query(downloadId3) == DownloadManager.STATUS_NOT_FOUND) {
                downloadId3 = downloadManager.add(downloadRequest3);
            }
        });
    }

    private void downloadImage2(Image imageView2, Button downloadImage2, ProgressBar progressBar2, RetryPolicy retryPolicy) {
        // 下载图片1
        Uri downloadUri1 = Uri.parse(FILE2);
        filesDirs2 = new File(getCacheDir(), "/test_photo2.png");
        Uri destinationUri1 = Uri.getUriFromFile(filesDirs2);
        downloadRequest2 = new DownloadRequest(downloadUri1)
                .setDestinationURI(destinationUri1)
                .setPriority(DownloadRequest.Priority.LOW)
                .setRetryPolicy(retryPolicy)
                .setDownloadContext("Download2")
                .setStatusListener(new DownloadStatusListenerV1() {
                    @Override
                    public void onDownloadComplete(DownloadRequest downloadRequest) {
                        imageView2.setPixelMap(ImageUtil.getPixelMapByFile(filesDirs2));
                        HiLogUtil.error("onDownloadComplete---完成下载-----" + filesDirs2.getTotalSpace() + "------");
                    }

                    @Override
                    public void onDownloadFailed(DownloadRequest downloadRequest, int errorCode, String errorMessage) {
                        HiLogUtil.error("onDownloadFailed---" + errorCode + "-----" + errorMessage + "-----");
                    }

                    @Override
                    public void onProgress(DownloadRequest downloadRequest, long totalBytes, long downloadedBytes, int progress) {
                        HiLogUtil.error("onProgress---" + progress + "-----");
                        progressBar2.setProgressValue(progress);
                    }
                });

        downloadImage2.setClickedListener(component -> {
            if (downloadManager.query(downloadId2) == DownloadManager.STATUS_NOT_FOUND) {
                downloadId2 = downloadManager.add(downloadRequest2);
            }
        });
    }

    private void downloadImage1(Image imageView1, Button downloadImage1, ProgressBar progressBar1, RetryPolicy retryPolicy) {
        // 下载图片1
        Uri downloadUri = Uri.parse(FILE1);
        filesDirs1 = new File(getCacheDir(), "/test_photo1.jpg");
        Uri destinationUri = Uri.getUriFromFile(filesDirs1);
        downloadRequest1 = new DownloadRequest(downloadUri)
                .setDestinationURI(destinationUri)
                .setPriority(DownloadRequest.Priority.LOW)
                .setRetryPolicy(retryPolicy)
                .setDownloadContext("Download1")
                .setStatusListener(new DownloadStatusListenerV1() {
                    @Override
                    public void onDownloadComplete(DownloadRequest downloadRequest) {
                        imageView1.setPixelMap(ImageUtil.getPixelMapByFile(filesDirs1));
                        HiLogUtil.error("onDownloadComplete---完成下载-----" + filesDirs1.getTotalSpace() + "------");
                    }

                    @Override
                    public void onDownloadFailed(DownloadRequest downloadRequest, int errorCode, String errorMessage) {
                        HiLogUtil.error("onDownloadFailed---" + errorCode + "-----" + errorMessage + "-----");
                    }

                    @Override
                    public void onProgress(DownloadRequest downloadRequest, long totalBytes, long downloadedBytes, int progress) {
                        HiLogUtil.error("onProgress---" + progress + "-----");
                        progressBar1.setProgressValue(progress);
                    }
                });

        downloadImage1.setClickedListener(component -> {
            if (downloadManager.query(downloadId1) == DownloadManager.STATUS_NOT_FOUND) {
                downloadId1 = downloadManager.add(downloadRequest1);
            }
        });
    }
}
